package com.zyp.nio;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author zhangyanping
 */
public class AcceptHandler implements NIOHandler {
    private final ServerSocketChannel channel;
    private final Selector selector;


    public AcceptHandler(ServerSocketChannel channel, Selector selector) {
        this.channel = channel;
        this.selector = selector;
    }

    @Override
    public void handle() {
        System.out.println("有人加入了");
        SocketChannel socketChannel = null;
        try {
            socketChannel = channel.accept();

            //配置读取处理器
            socketChannel.configureBlocking(false);
            SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
            key.attach(new MsgHandler(socketChannel, key));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
